import https from 'https';
import http from 'http';

// 是否为https协议
const isHttpsRegExp = /^https\:\/\//;

// 请求方法
const request = (url: string, timeout: number, fn: (res: http.IncomingMessage) => void) => {
	if (isHttpsRegExp.test(url)) {
		return https.get(
			url,
			{
				timeout,
				rejectUnauthorized: false,
			},
			fn
		);
	} else {
		return http.get(url, { timeout }, fn);
	}
};

export function downloadFile(
	url: string,
	onProgress?: (progress: number, cur: number, total: number) => void,
	timeout: number = 10000
) {
	return new Promise<Buffer>((resolve, reject) => {
		const req = request(url, timeout, (res) => {
			// 设置编码格式
			res.setEncoding('binary');

			// 文件总长度
			let totalLength = parseInt(res.headers['content-length'] as string, 10) || 0;
			// 已经下载的数据长度
			let cur = 0;
			// 当前进度百分比
			let progress = 0;

			let chunks: string = '';

			onProgress && onProgress(0, cur, totalLength);
			res.on('data', (chunk: string) => {
				chunks += chunk;
				cur += chunk.length;
				progress = +((100.0 * cur) / totalLength).toFixed(2); // 计算当前进度
				onProgress && onProgress(progress, cur, totalLength);
			});

			res.on('end', () => {
				if (res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300) {
					if (progress < 100) {
						onProgress && onProgress(100, cur, totalLength);
					}

					resolve(Buffer.from(chunks, 'binary'));
				} else {
					reject(res.statusCode);
				}
			});

			res.on('error', (err) => {
				reject(err);
			});
		});

		req.on('error', (err) => {
			reject(err);
		});

		req.on('timeout', () => {
			req.destroy();

			reject(new Error('timeout'));
		});
	});
}
